<?php
/**
 * @author css3 <css3@qq.com>
 */

namespace zonday\weixin\store;
use Yii;

/**
 * Class FileStore
 */
class FileStore extends Store
{
    private $_store = [];

    public function read($name)
    {
        if (isset($this->_store[$name])) {
            return $this->_store[$name];
        }

        $storeFile = $this->storeFile($name);
        if (file_exists($storeFile)) {
            $this->_store[$name] = json_decode(file_get_contents($storeFile), true);
            return $this->_store[$name];
        }  else {
            return false;
        }
    }

    public function write($name, array $data)
    {
        $storeFile = $this->storeFile($name);
        file_put_contents($storeFile, json_encode($data));
        $this->_store[$name] = $data;
    }

    protected function storeFile($name)
    {
        return Yii::getAlias('@runtime') . DIRECTORY_SEPARATOR . '__weixin_store_' . $name . '.json';
    }
}
